import { ref, createApp, type Component, type App, inject } from 'vue';
import Window from '@/views/im/window/Window.vue';

interface ComponentWindow {
  id: number;
  component: Component;
  title: string;
  width: string;
  height: string;
  x: number;
  y: number;
}

class WindowManager {
  private static instance: WindowManager;
  private windows: ComponentWindow[];
  private zIndex: number;

  private constructor() {
    this.windows = [];
    this.zIndex = 9999;
  }

  public static getManager() {
    if (!this.instance) {
      this.instance = new WindowManager();
    }
    return this.instance;
  }

  private createWindow(component: Component, title: string, width: string, height: string) {
    const app = createApp(Window, {
      title,
      width,
      height
    });

    const id = this.getNextWindowId();

    const close = () => {
      const index = this.getWindowIndex(id);
      if (index >= 0) {
        this.windows.splice(index, 1);
      }
    };

    const windowComponent = app.mount(document.createElement('div'));

    windowComponent.appContext.provides.$close = close;

    this.windows.push({ id, component, title, width, height, x: 0, y: 0 });

    return { id, windowComponent };
  }

  private getNextWindowId() {
    return this.windows.length > 0 ? this.windows[this.windows.length - 1].id + 1 : 1;
  }

  private getWindowIndex(windowId: number) {
    return this.windows.findIndex(w => w.id === windowId);
  }

  public open(component: Component, title: string, width: string, height: string) {
    const { id, windowComponent } = this.createWindow(component, title, width, height);
    windowComponent.$el.style.zIndex = (this.zIndex++).toString();
    document.body.appendChild(windowComponent.$el);
    return id;
  }

  public close(windowId: number) {
    const index = this.getWindowIndex(windowId);
    if (index >= 0) {
      const window = this.windows[index];
      const app = window.component.appContext.app;
      if (app) {
        app.unmount();
      }
      this.windows.splice(index, 1);
      const el = window.component.$el;
      if (el) {
        el.parentNode?.removeChild(el);
      }
    }
  }
}

const WindowManagerKey = Symbol('WindowManager');

export function openWindow(component: Component, title: string, width: string, height: string) {
  const { open } = (inject(WindowManagerKey) as WindowManager);
  return open(component, title, width, height);
}

export function closeWindow(id: number) {
  const { close } = (inject(WindowManagerKey) as WindowManager);
  close(id);
}

export default function install(app: App) {
  const windowManager = WindowManager.getManager();

  app.provide(WindowManagerKey, windowManager);

  // 创建一个全局方法$window，用于快速打开窗口
  app.config.globalProperties.$window = {
    open: windowManager.open.bind(windowManager),
    close: windowManager.close.bind(windowManager)
  };
}